package com.lz.library.utils

import android.os.Environment
import android.text.TextUtils
import com.lz.library.BuildConfig
import com.lz.library.extension.APP
import java.io.Closeable
import java.io.File
import java.io.FileWriter
import java.io.IOException
import java.text.DecimalFormat

object FileUtils {

    /**
     * 缓存文件根目录名
     */
    private const val FILE_DIR: String = BuildConfig.appName

    /**
     * 上传的照片文件路径
     */
    private const val UPLOAD_FILE = "upload"

    /**
     * 下载路径
     */
    private const val DOWNLOAD_FILE = "download"

    /**
     * SD卡是否存在
     */
    @JvmStatic
    fun isSDCardExist() = Environment.getExternalStorageState() == Environment.MEDIA_MOUNTED

    @JvmStatic
    fun getCacheDir(): File {
        val dir = if (isSDCardExist()) {
//            if (hasQ()) APP.externalCacheDir else Environment.getExternalStorageDirectory()
            Environment.getExternalStorageDirectory()
        } else APP.cacheDir
        return File(dir, FILE_DIR).apply { if (!exists()) mkdirs() }
    }

    @JvmStatic
    fun getExternalDir(): File {
        val dir = if (isSDCardExist()) APP.externalCacheDir else APP.cacheDir
        return File(dir, FILE_DIR).apply { if (!exists()) mkdirs() }
    }

    /**
     * 获取上传路径
     * @return
     */
    @JvmStatic
    fun getUploadFile() = File(getCacheDir(), UPLOAD_FILE).apply { if (!exists()) mkdirs() }

    /**
     * 获取下载路径
     * @return
     */
    @JvmStatic
    fun getDownloadFile() = File(getCacheDir(), DOWNLOAD_FILE).apply { if (!exists()) mkdirs() }


    /**
     * 获取文件路径下所有文件大小, 适当放到子线程中执行
     *
     * @param file
     * @return
     */
    @JvmStatic
    fun getFileSize(file: File?): Long {
        return if (file?.exists() == true) {
            if (file.isDirectory) {
                var total = 0L
                file.listFiles()?.forEach { total += getFileSize(it) }
                total
            } else file.length()
        } else 0
    }

    /**
     * 删除文件夹下所有文件,适当放到子线程中执行
     *
     * @param file
     */
    @JvmStatic
    fun deleteFiles(file: File) {
        if (file.exists()) {
            if (file.isDirectory) {
                file.listFiles()?.forEach { deleteFiles(it) }
            } else {
                file.delete()
            }
        }
    }


    /**
     * 关闭资源
     *
     * @param closes
     */
    @JvmStatic
    fun closeCloseable(vararg closes: Closeable?) {
        closes.forEach {
            try {
                it?.close()
            } catch (_: IOException) {
            }
        }
    }

    /**
     * 文件大小
     *
     * @param fileS
     * @return
     */
    @JvmStatic
    fun formatFileSize(fileS: Long): String {
        return when {
            fileS <= 0 -> "0B"
            fileS < 1024 -> DecimalFormat("#.00").format(fileS.toDouble()) + "B"
            fileS < 1048576 -> DecimalFormat("#.00").format(fileS.toDouble() / 1024) + "KB"
            fileS < 1073741824 -> DecimalFormat("#.00").format(fileS.toDouble() / 1048576) + "MB"
            else -> DecimalFormat("#.00").format(fileS.toDouble() / 1073741824) + "GB"
        }
    }

    /**
     * 将字符串写入文件中
     * @param str 需要写入的字符串
     * @param file 写入文件的路径
     * @param append  true 追加写入 false 覆盖写入
     * @return
     */
    @JvmStatic
    fun writeFile(str: String, file: File, append: Boolean): Boolean {
        if (!TextUtils.isEmpty(str)) {
            try {
                return FileWriter(file, append).use { it.write(str); it.flush(); true }
            } catch (_: Exception) {
            }
        }
        return false
    }

}